import { Form, Input, Button, message } from "antd";
import { useForm } from "antd/es/form/Form";
import { useNavigate } from "react-router-dom";
import { updatePassword, updatePasswordCaptcha } from "@api/updatepassword";
import "./index.less";

export interface UpdatePassword {
    email: string;
    captcha: string;
    password: string;
    confirmPassword: string;
}
const layout1 = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}

export function UpdatePassword() {
    const [form] = useForm();
    const navigate = useNavigate();

    const sendCaptcha = async () => {
        const address = form.getFieldValue('email');
        if (!address) return message.error('请输入邮箱地址');
        try {
            const resp = await updatePasswordCaptcha(address);
            message.success('发送成功');
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }
    const onFinish = async (values: UpdatePassword) => {
        if (values.confirmPassword !== values.password) return message.error('两次密码不一致');
        try {
            const res = await updatePassword(values);
            message.success('密码修改成功');
            setTimeout(() => {
                navigate('/login');
            }, 1500);
        } catch (error: any) {
            message.error(error?.data?.message || '系统繁忙，请稍后重试');
        }
    }


    return <div className="update-password">
        <h1>聊天室系统</h1>
        <Form
            form={form}
            {...layout1}
            colon={false}
            autoComplete="off"
            onFinish={onFinish}
        >
            <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input />
            </Form.Item>
            <Form.Item label="邮箱" name="email" rules={[{ required: true, message: '请输入邮箱' }, { type: 'email', message: '请输入合法的邮箱格式' }]}>
                <Input />
            </Form.Item>

            <div className="update-password_captcha">
                <Form.Item label="验证码" name="captcha" rules={[{ required: true, message: '请输入验证码' }]}>
                    <Input />
                </Form.Item>
                <Button type="primary" onClick={sendCaptcha}>发送验证码</Button>
            </div>

            <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
                <Input.Password />
            </Form.Item>
            <Form.Item label="确认密码" name="confirmPassword" rules={[{ required: true, message: '请输入确认密码' }]}>
                <Input />
            </Form.Item>
            <Form.Item label=" ">
                <Button className="update-password_btn" type="primary" htmlType="submit">修改</Button>
            </Form.Item>
        </Form>
    </div>
}